var Voc = {}

Voc._count = 0;

Voc.init = function() {
  localVoc = [];
  var count = 0;
  for (var i = 0; i < localStorage.length; i++) {
    var key = localStorage.key(i);
    if (!key.indexOf(bgPage.SHEET_VOC_NAME)) {
      var id = parseInt(key.substring(bgPage.SHEET_VOC_NAME.length));
      if (id) {
        count++;
        localVoc[id] = JSON.parse(localStorage[key]); 
      }
    }
  }
  if (count) { utils.updateBadge(count); }
  Voc._count = count;
  return count > 0;
};

Voc._save = function(term) {
  if(term) {
    var t = JSON.stringify(term);
    localStorage[bgPage.SHEET_VOC_NAME + term.id] = t;
    // Save into gdocs
    localVoc[term.id] = term;
    return true;
  }
  return false;
};

Voc.addTerm = function(term) {
  if (Voc._save(term)) {
    Voc._count++;
    utils.updateBadge(Voc._count);
  }
};

Voc.updateTerm = function(term) { Voc._save(term); };

Voc.deleteTerm = function(term) {
	if(term && term instanceof Number) {
    delete localVoc[term];
    localStorage.removeItem(term);
	} else {
    delete localVoc[term.id];
    localStorage.removeItem(term.id);
	}
	Voc._count--;
  utils.updateBadge(Voc._count);
};
	

Voc.updateStore = function () {
  for (var p in localVoc) {
    var id = parseInt(p);
    if (id) { localStorage[bgPage.SHEET_VOC_NAME + id] = JSON.stringify(localVoc[id]); }
  }
};

Voc.getTerm = function(id) { return new Term(localVoc[id]); };

Voc.getRandomTerm = function() {
  var index = Math.floor(Math.random() * Voc._count);
  var i = 0;
  
  for (var key in localVoc) {
    if (i >= index) {
      var t = Voc.getTerm(key);
      if (t.isReadyToUse) { return t; }
    }
    i++;
  }
  for (var key in localVoc) {
    var t = Voc.getTerm(key);
    if (t.isReadyToUse) { return t; }
    if (i >= index) {
      break;
    }
    i++;
  }
  
  return new Term('undefined', 'undefined');
}

Voc.getCount = function() { return Voc._count; } 
Voc.each = function(f) {
  if (!f) { return; }
  for (var id in localVoc) {
    f(localVoc[id]);
  }
} 

